﻿using UnityEngine;
using System;
using System.Collections;
using System.Net.Sockets;

public class PlayerControl : MonoBehaviour {
	public bool isPlayer;
	private Server server;
	private Socket Remote;
	private float timeStamp;

	// Use this for initialization
	void Start() {
		server = GameObject.Find("ServerHandler").GetComponent<Server>();
		if(isPlayer)
			Remote = server.GetSocket();
	}
	
	// Update is called once per frame
	void Update () {
		if(!isPlayer || (isPlayer && server.isPrimary))
			return;

		if(Time.time - timeStamp > 0.1) {
			SendPosition(transform.position);
			timeStamp = Time.time;
		}
	}

	public void Attack(RemotePlayer playerNumber) {
		var victim = server.GetPlayerNumber(playerNumber);
		if(victim == -1) {
			Debug.Log ("Unable to find player!");
			return;
		}

		var bytes = new byte[6];
		BitConverter.GetBytes(RemotePlayer.COMMAND_ATTACK).CopyTo(bytes, 0);
		BitConverter.GetBytes(victim).CopyTo(bytes, 2);
		BitConverter.GetBytes(server.me).CopyTo(bytes, 4);

		Remote.Send(bytes);			
	}
	
	public void SendPosition(Vector2 pos) {
		if(Remote == null) return;
		var bytes = transform.SerializePosition();
		
		Remote.Send(bytes);
	}
}
